package redis;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import util.RedisUtil;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 放入缓存/读取缓存
 *
 * @author zhanglinfeng
 * @date create in 2022/8/31 11:17
 */
@Aspect
public class RedisReadAspect implements Ordered {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisReadAspect.class);
    @Resource
    private RedissonClient redissonClient;

    @Override
    public int getOrder() {
        return 4;
    }

    @Pointcut("@annotation(redis.RedisRead)")
    public void pointcut() {
    }

    @Around(value = "pointcut()&&@annotation(redisRead)")
    public Object doAspect(ProceedingJoinPoint joinPoint, RedisRead redisRead) throws Throwable {
        Object[] args = joinPoint.getArgs();
        //获取缓存key
        String cacheKey = RedisUtil.getKey(args, redisRead.cacheKey(), redisRead.cacheIndex());
        // 从缓存读取数据
        RBucket<Object> rBucket = redissonClient.getBucket(cacheKey);
        if (rBucket.isExists()) {
            return rBucket.get();
        } else {
            Object obj = joinPoint.proceed(args);
            rBucket.set(obj, redisRead.cacheExpire(), TimeUnit.MILLISECONDS);
            LOGGER.info("key:{},放入缓存，有效时间：{}", cacheKey, redisRead.cacheExpire());
            return obj;
        }
    }
}
